package com.geo.content.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.geo.content.entity.MediaFile;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 媒体文件Mapper接口
 */
@Mapper
public interface MediaFileMapper extends BaseMapper<MediaFile> {
    
    /**
     * 根据用户ID查询文件列表
     */
    @Select("SELECT * FROM media_files WHERE user_id = #{userId} AND deleted = 0 ORDER BY created_at DESC")
    List<MediaFile> findByUserId(@Param("userId") String userId);
    
    /**
     * 根据文件类型查询
     */
    @Select("SELECT * FROM media_files WHERE file_type = #{fileType} AND deleted = 0")
    List<MediaFile> findByFileType(@Param("fileType") String fileType);
    
    /**
     * 根据处理状态查询
     */
    @Select("SELECT * FROM media_files WHERE processing_status = #{status} AND deleted = 0")
    List<MediaFile> findByProcessingStatus(@Param("status") String status);
    
    /**
     * 根据存储路径查询文件
     */
    @Select("SELECT * FROM media_files WHERE storage_path = #{storagePath} AND deleted = 0")
    MediaFile findByStoragePath(@Param("storagePath") String storagePath);
    
    /**
     * 更新处理状态
     */
    @Update("UPDATE media_files SET processing_status = #{status}, updated_at = NOW() WHERE id = #{fileId}")
    int updateProcessingStatus(@Param("fileId") String fileId, @Param("status") String status);
    
    /**
     * 更新文件大小
     */
    @Update("UPDATE media_files SET file_size = #{fileSize}, updated_at = NOW() WHERE id = #{fileId}")
    int updateFileSize(@Param("fileId") String fileId, @Param("fileSize") Long fileSize);
    
    /**
     * 根据文件大小范围查询
     */
    @Select("SELECT * FROM media_files WHERE file_size >= #{minSize} AND file_size <= #{maxSize} AND deleted = 0")
    List<MediaFile> findByFileSizeRange(@Param("minSize") Long minSize, @Param("maxSize") Long maxSize);
    
    /**
     * 根据上传时间范围查询
     */
    @Select("SELECT * FROM media_files WHERE created_at >= #{startTime} AND created_at <= #{endTime} AND deleted = 0")
    List<MediaFile> findByUploadTimeRange(@Param("startTime") LocalDateTime startTime, 
                                         @Param("endTime") LocalDateTime endTime);
    
    /**
     * 查询需要清理的临时文件
     */
    @Select("SELECT * FROM media_files WHERE is_temporary = 1 AND created_at < #{expireTime} AND deleted = 0")
    List<MediaFile> findExpiredTempFiles(@Param("expireTime") LocalDateTime expireTime);
    
    /**
     * 根据内容ID查询关联的媒体文件
     */
    @Select("SELECT * FROM media_files WHERE content_id = #{contentId} AND deleted = 0")
    List<MediaFile> findByContentId(@Param("contentId") String contentId);
    
    /**
     * 根据文件哈希值查询文件
     */
    @Select("SELECT * FROM media_files WHERE file_hash = #{hash} AND deleted = 0 LIMIT 1")
    MediaFile selectByHash(@Param("hash") String hash);
}